package cn.liangcaomei.eduservice.listener;

import cn.liangcaomei.eduservice.entity.EduSubject;
import cn.liangcaomei.eduservice.entity.excel.SubjectData;
import cn.liangcaomei.eduservice.service.EduSubjectService;
import cn.liangcaomei.servicebase.exceptionhandler.CustException;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

public class SubjectExcelListener extends AnalysisEventListener<SubjectData> {

    //因爲 SubjectExcelListener 不能交給spring管理，需要自己new，不能注入對象
    public EduSubjectService subjectService;

    public SubjectExcelListener(){
    }

    public SubjectExcelListener(EduSubjectService subjectService){
        this.subjectService = subjectService;
    }

    //一行一行讀取excel文件内容
    @Override
    public void invoke(SubjectData subjectData, AnalysisContext analysisContext) {
        if (subjectData == null) {
            throw new CustException(2001,"文件數據爲空");
        }

        //一行一行讀取，每次讀取兩個值，第一個值一級分類，第二個值二級分類
        //判斷一級分類是否爲空
        EduSubject existOneSubject = this.existOneSubject(subjectService, subjectData.getOneSubjectName());
        if (existOneSubject == null) {
            existOneSubject = new EduSubject();
            existOneSubject.setParentId("0");
            existOneSubject.setTitle(subjectData.getOneSubjectName());
            subjectService.save(existOneSubject);
        }

        //獲取一級分類的id
        String pid = existOneSubject.getId();
        //判斷二級分類是否爲空
        EduSubject existTwoSubject = this.existTwoSubject(subjectService, subjectData.getTwoSubjectName(), pid);
        if (existTwoSubject == null) {
            existTwoSubject = new EduSubject();
            existTwoSubject.setParentId(pid);
            existTwoSubject.setTitle(subjectData.getTwoSubjectName());
            subjectService.save(existTwoSubject);
        }

    }

    //判斷一級分類不能重複添加
    private EduSubject existOneSubject(EduSubjectService subjectService,String name){
        QueryWrapper<EduSubject> wrapper = new QueryWrapper<>();
        wrapper.eq("title",name);
        wrapper.eq("parent_id",0);
        EduSubject oneSubject = subjectService.getOne(wrapper);
        return oneSubject;
    }
    //判斷二級分類不能重複添加
    private EduSubject existTwoSubject(EduSubjectService subjectService,String name,String pid){
        QueryWrapper<EduSubject> wrapper = new QueryWrapper<>();
        wrapper.eq("title",name);
        wrapper.eq("parent_id",pid);
        EduSubject twoSubject = subjectService.getOne(wrapper);
        return twoSubject;
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {

    }
}
